<template>
    <div class="map-container">
        <!-- 地图容器 -->
        <div id="map-container" class="map">
            <!-- 中心定位图标 -->
            <div class="center-location">
                <img src="@/assets/images/location.png" alt="当前位置">
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-bar">
            <div class="input-group start">
                <input type="text" v-model="startAddress" placeholder="请输入起点" @input="searchStart">
                <div class="search-results" v-if="startResults.length">
                    <div v-for="(item, index) in startResults" :key="index" class="result-item"
                        @click="selectStart(item)">
                        {{ item.title }}
                    </div>
                </div>
            </div>
            <div class="input-group end">
                <input type="text" v-model="endAddress" placeholder="请输入终点" @input="searchEnd">
                <div class="search-results" v-if="endResults.length">
                    <div v-for="(item, index) in endResults" :key="index" class="result-item" @click="selectEnd(item)">
                        {{ item.title }}
                    </div>
                </div>
            </div>
            <div class="search-btn" @click="planRoute">开始导航</div>
        </div>

        <!-- 右下角定位按钮 -->
        <div class="location-btn" @click="getCurrentLocation" :class="{
            'locating': isLocating,
            'moved-up': routeInfo
        }">
            <img src="@/assets/images/location.png" alt="定位">
        </div>

        <!-- 路线信息 -->
        <div class="route-info" v-if="routeInfo">
            <div class="travel-modes">
                <div class="mode-item" :class="{ active: currentMode === 'driving' }" @click="switchMode('driving')">
                    <i class="iconfont icon-car"></i>
                    <span>驾车</span>
                    <span class="time" v-if="modeTimes.driving">{{ modeTimes.driving }}</span>
                </div>
                <div class="mode-item" :class="{ active: currentMode === 'transit' }" @click="switchMode('transit')">
                    <i class="iconfont icon-bus"></i>
                    <span>公交地铁</span>
                    <span class="time" v-if="modeTimes.transit">{{ modeTimes.transit }}</span>
                </div>
                <div class="mode-item" :class="{ active: currentMode === 'walking' }" @click="switchMode('walking')">
                    <i class="iconfont icon-walk"></i>
                    <span>步行</span>
                    <span class="time" v-if="modeTimes.walking">{{ modeTimes.walking }}</span>
                </div>
            </div>

            <div class="route-summary">
                <div class="info-header">路线详情</div>
                <div class="summary-info">
                    <div class="distance">总距离：{{ routeInfo.distance }}</div>
                    <div class="duration">预计时间：{{ routeInfo.duration }}</div>
                </div>
            </div>

            <div class="route-steps" v-if="routeInfo.steps">
                <div class="step-item" v-for="(step, index) in routeInfo.steps" :key="index">
                    <div class="step-number">{{ index + 1 }}</div>
                    <div class="step-content" v-html="step.instructions"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { showToast, showLoadingToast, closeToast } from 'vant';

const AK = 'd48HOBz30drfL1WX5SCxaldwctYWKBP1';
let map = null;
let localSearch = null;
let driving = null;
let transit = null;
let walking = null;

const startAddress = ref('');
const endAddress = ref('');
const startResults = ref([]);
const endResults = ref([]);
const routeInfo = ref(null);
const startPoint = ref(null);
const endPoint = ref(null);

// 添加定位状态
const isLocating = ref(false);

const currentMode = ref('driving'); // 当前出行方式

// 添加各个出行方式的时间
const modeTimes = ref({
    driving: '',
    transit: '',
    walking: ''
});

// 初始化地图
const initMap = () => {
    map = new BMapGL.Map("map-container");
    const defaultPoint = new BMapGL.Point(116.404, 39.915);
    map.centerAndZoom(defaultPoint, 15);
    map.enableScrollWheelZoom(true);

    // 初始化本地搜索和路线规划
    localSearch = new BMapGL.LocalSearch(map, {
        renderOptions: { map: map }
    });

    // 初始化路线规划服务
    initRouteServices();

    // 初始化完成后立即获取当前位置
    getCurrentLocation();
};

// 搜索起点
const searchStart = () => {
    if (startAddress.value.trim()) {
        localSearch.search(startAddress.value);
        localSearch.setMarkersSetCallback((pois) => {
            startResults.value = pois;
        });
    }
};

// 搜索终点
const searchEnd = () => {
    if (endAddress.value.trim()) {
        localSearch.search(endAddress.value);
        localSearch.setMarkersSetCallback((pois) => {
            endResults.value = pois;
        });
    }
};

// 选择起点
const selectStart = (item) => {
    startAddress.value = item.title;
    startPoint.value = item.point;
    startResults.value = [];
};

// 选择终点
const selectEnd = (item) => {
    endAddress.value = item.title;
    endPoint.value = item.point;
    endResults.value = [];
};

// 处理路线规划结果
const handleRouteResult = (results) => {
    if (!results.getNumPlans()) return;

    const plan = results.getPlan(0);
    const steps = [];

    if (currentMode.value === 'transit') {
        // 处理公交路线
        const lines = plan.getNumLines();
        for (let i = 0; i < lines; i++) {
            const line = plan.getLine(i);
            if (line) {
                steps.push({
                    instructions: line.title || '步行到达下一站',
                    distance: line.distance || '未知距离'
                });
            }
        }
    } else {
        // 处理驾车和步行路线
        if (plan.getRoutes && plan.getRoutes().length > 0) {
            plan.getRoutes().forEach(route => {
                if (route) {
                    steps.push({
                        instructions: route.title || route.instructions || '直行',
                        distance: route.distance || '未知距离'
                    });
                }
            });
        }
    }

    routeInfo.value = {
        distance: plan.getDistance(true) || '计算中',
        duration: plan.getDuration(true) || '计算中',
        steps: steps
    };
};

// 修改初始化路线规划服务的函数
const initRouteServices = () => {
    // 驾车路线规划
    driving = new BMapGL.DrivingRoute(map, {
        renderOptions: {
            map: map,
            autoViewport: true,
            enableDragging: true,
            panel: 'route-steps' // 可以尝试使用百度地图自带的路线面板
        },
        onSearchComplete: handleRouteResult,
        onPolylinesSet: function () {
            showToast({
                message: '路线规划完成',
                position: 'bottom',
            });
        }
    });

    // 公交路线规划
    transit = new BMapGL.TransitRoute(map, {
        renderOptions: {
            map: map,
            autoViewport: true,
            enableDragging: true,
            panel: 'route-steps'
        },
        onSearchComplete: handleRouteResult,
        onPolylinesSet: function () {
            showToast({
                message: '路线规划完成',
                position: 'bottom',
            });
        }
    });

    // 步行路线规划
    walking = new BMapGL.WalkingRoute(map, {
        renderOptions: {
            map: map,
            autoViewport: true,
            enableDragging: true,
            panel: 'route-steps'
        },
        onSearchComplete: handleRouteResult,
        onPolylinesSet: function () {
            showToast({
                message: '路线规划完成',
                position: 'bottom',
            });
        }
    });
};

// 切换出行方式
const switchMode = (mode) => {
    currentMode.value = mode;
    map.clearOverlays();
    planRoute();
};

// 修改路线规划函数
const planRoute = () => {
    if (!startPoint.value || !endPoint.value) return;

    showLoadingToast({
        message: '正在规划路线...',
        duration: 0,
    });

    // 获取所有出行方式的时间
    calculateAllModeTimes();

    try {
        switch (currentMode.value) {
            case 'driving':
                driving.search(startPoint.value, endPoint.value);
                break;
            case 'transit':
                transit.search(startPoint.value, endPoint.value);
                break;
            case 'walking':
                walking.search(startPoint.value, endPoint.value);
                break;
        }
    } catch (error) {
        console.error('路线规划错误:', error);
        showToast({
            message: '路线规划失败，请重试',
            position: 'bottom',
        });
    } finally {
        closeToast();
    }
};

// 计算所有出行方式的时间
const calculateAllModeTimes = () => {
    // 驾车时间
    const drivingRoute = new BMapGL.DrivingRoute(map, {
        onSearchComplete: function (results) {
            if (results.getNumPlans() > 0) {
                modeTimes.value.driving = results.getPlan(0).getDuration(true);
            }
        }
    });
    drivingRoute.search(startPoint.value, endPoint.value);

    // 公交时间
    const transitRoute = new BMapGL.TransitRoute(map, {
        onSearchComplete: function (results) {
            if (results.getNumPlans() > 0) {
                modeTimes.value.transit = results.getPlan(0).getDuration(true);
            }
        }
    });
    transitRoute.search(startPoint.value, endPoint.value);

    // 步行时间
    const walkingRoute = new BMapGL.WalkingRoute(map, {
        onSearchComplete: function (results) {
            if (results.getNumPlans() > 0) {
                modeTimes.value.walking = results.getPlan(0).getDuration(true);
            }
        }
    });
    walkingRoute.search(startPoint.value, endPoint.value);
};

// 修改获取当前位置的函数
const getCurrentLocation = async () => {
    if (!map || isLocating.value) return;

    isLocating.value = true;
    showLoadingToast({
        message: '正在定位...',
        duration: 0,
    });

    try {
        // 先尝试使用百度地图定位
        const point = await new Promise((resolve, reject) => {
            const geolocation = new BMapGL.Geolocation();
            geolocation.enableSDKLocation();

            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    resolve(r.point);
                } else {
                    reject(new Error('百度地图定位失败'));
                }
            }, {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0,
                SDKLocation: true
            });
        });

        map.centerAndZoom(point, 15);

        // 获取地址信息
        const address = await new Promise((resolve, reject) => {
            const geoc = new BMapGL.Geocoder();
            geoc.getLocation(point, function (rs) {
                if (rs) {
                    const addComp = rs.addressComponents;
                    resolve(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber);
                } else {
                    reject(new Error('获取地址失败'));
                }
            });
        });

        startAddress.value = address;
        startPoint.value = point;

        showToast({
            message: '定位成功',
            position: 'bottom',
        });

    } catch (error) {
        console.error('定位错误:', error);
        showToast({
            message: '定位失败，请检查定位权限或网络连接',
            position: 'bottom',
        });
    } finally {
        closeToast();
        isLocating.value = false;
    }
};

// 修改加载百度地图脚本的函数
const loadBaiduMapScript = () => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        // 添加所需的库和参数
        script.src = `https://api.map.baidu.com/api?v=3.0&type=webgl&ak=${AK}&callback=initBaiduMap&s=1&plugins=Geolocation`;
        script.onerror = reject;
        document.head.appendChild(script);
        window.initBaiduMap = () => {
            resolve();
        };
    });
};

onMounted(async () => {
    try {
        await loadBaiduMapScript();
        initMap();
    } catch (error) {
        console.error('百度地图加载失败:', error);
    }
});

onUnmounted(() => {
    // 清理地图实例
    if (map) {
        map.destroy();
    }
});
</script>

<style lang="scss" scoped>
.map-container {
    width: 100%;
    height: 100vh;
    position: relative;
    background: #f5f5f5;

    .search-bar {
        position: absolute;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        width: 90%;
        max-width: 400px;
        background: white;
        padding: 15px;
        border-radius: 12px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        z-index: 100;

        .input-group {
            position: relative;
            margin-bottom: 10px;

            input {
                width: 100%;
                height: 40px;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 0 15px;
                font-size: 14px;
                outline: none;

                &:focus {
                    border-color: variables.$firColor;
                }

                &::placeholder {
                    color: #999;
                    font-size: 13px;
                }
            }

            .search-results {
                position: absolute;
                top: 100%;
                left: 0;
                right: 0;
                background: white;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                max-height: 200px;
                overflow-y: auto;

                .result-item {
                    padding: 10px 15px;
                    cursor: pointer;

                    &:hover {
                        background: #f5f5f5;
                    }
                }
            }
        }

        .search-btn {
            background: #8B5CF6;
            color: white;
            text-align: center;
            padding: 10px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
                background: #7C3AED;
                box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3);
            }
        }
    }

    .map {
        width: 100%;
        height: 100%;
        position: relative;

        .center-location {
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 40px;
            height: 40px;
            z-index: 99;
            pointer-events: none;

            img {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }
        }
    }

    .location-btn {
        position: fixed;
        right: 20px;
        bottom: 30px;
        width: 44px;
        height: 44px;
        background: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        z-index: 100;
        transition: all 0.3s ease;

        &.moved-up {
            bottom: 250px;
        }

        img {
            width: 24px;
            height: 24px;
            object-fit: contain;
        }

        &:active {
            transform: scale(0.95);
        }

        &:hover {
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
        }

        &.locating {
            animation: rotate 1s linear infinite;
            background: #8B5CF6;

            img {
                filter: brightness(0) invert(1);
            }
        }
    }

    .route-info {
        position: absolute;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        width: 90%;
        max-width: 400px;
        background: rgba(255, 255, 255, 0.95);
        padding: 15px;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        z-index: 99;

        .travel-modes {
            display: flex;
            justify-content: space-around;
            margin-bottom: 15px;
            border-bottom: 2px solid #f5f5f5;
            padding-bottom: 10px;

            .mode-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 10px 20px;
                cursor: pointer;
                border-radius: 8px;
                transition: all 0.3s ease;
                position: relative;

                i {
                    font-size: 24px;
                    margin-bottom: 4px;
                }

                span {
                    font-size: 14px;
                    font-weight: 500;
                }

                .time {
                    font-size: 12px;
                    color: #7C3AED;
                    margin-top: 4px;
                    opacity: 0.8;

                    .active & {
                        color: white;
                    }
                }

                &.active {
                    background: #8B5CF6;
                    color: white;
                    transform: scale(1.05);
                    box-shadow: 0 2px 12px rgba(139, 92, 246, 0.4);

                    .time {
                        color: white;
                    }
                }

                &:hover {
                    background: rgba(139, 92, 246, 0.1);
                    color: #8B5CF6;
                }
            }
        }

        .route-summary {
            margin-bottom: 15px;
            padding: 10px;
            background: rgba(139, 92, 246, 0.05);
            border-radius: 8px;
            border: 1px solid rgba(139, 92, 246, 0.1);

            .info-header {
                font-size: 16px;
                font-weight: bold;
                color: #222;
                margin-bottom: 10px;
            }

            .summary-info {
                display: flex;
                justify-content: space-between;

                .distance,
                .duration {
                    font-size: 15px;
                    color: #7C3AED;
                    font-weight: 500;
                }
            }
        }

        .route-steps {
            max-height: 200px;
            overflow-y: auto;
            padding-right: 10px;

            .step-item {
                display: flex;
                margin-bottom: 12px;
                padding-bottom: 12px;
                border-bottom: 1px dashed #e0e0e0;
                padding: 10px;
                transition: all 0.3s ease;

                &:hover {
                    background: rgba(139, 92, 246, 0.05);
                    border-radius: 6px;
                }

                .step-number {
                    width: 24px;
                    height: 24px;
                    background: #8B5CF6;
                    color: white;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 14px;
                    font-weight: bold;
                    margin-right: 10px;
                    flex-shrink: 0;
                    box-shadow: 0 2px 6px rgba(139, 92, 246, 0.3);
                }

                .step-content {
                    font-size: 15px;
                    line-height: 1.4;
                    color: #333;
                    padding: 2px 0;
                }
            }

            &::-webkit-scrollbar {
                width: 6px;
            }

            &::-webkit-scrollbar-thumb {
                background: #ccc;
                border-radius: 3px;
            }

            &::-webkit-scrollbar-track {
                background: #f5f5f5;
                border-radius: 3px;
            }
        }
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}
</style>
